package wanba.wanbatv.com.wudao.activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;


import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;

import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import de.hdodenhof.circleimageview.CircleImageView;
import wanba.wanbatv.com.wudao.R;
import wanba.wanbatv.com.wudao.util.Behavior;
import wanba.wanbatv.com.wudao.util.DataReport;
import wanba.wanbatv.com.wudao.util.ProductInfo;
import wanba.wanbatv.com.wudao.util.Util;
import wanba.wanbatv.com.wudao.util.WanbaMediaPlayer;


/**
 * 全屏播放器
 * 
 * @author zhangyus
 *
 */
public class SimplewudaoPlayerActivity extends FullScreenActivity {

	//标记快进快退按键状态：正常，未进行快进快退操作
	private static final int STATE_FAST_SEEK_IDLE = 0;
	//标记快进快退按键状态：用户长按着按键，但还未开始快进快退
	private static final int STATE_FAST_SEEK_PREPARED = 1;
	//标记快进快退按键状态：已经开始快进快退
	private static final int STATE_FAST_SEEK_START = 2;
//	MediaController mc;
	VideoView mVideoView;
	private long exitTime;
	ProgressDialog dialog2;
	SurfaceView surfaceView;
	String appName;
	String loading;
	String exitInfo;

	View bofang_view;
	ImageView playstat;
	ImageView playstop;
	ImageView playback;
	ImageView playgo;
	ProgressBar playprogressbar;
	Thread mThread;
	private boolean isRunning = true;
	WanbaMediaPlayer mediaPlayer=null;
	ProgressBar pro_mid;
	TextView kaluli_tv;
	static float kaluli = 0.0f;
	static int duration=0;
	static String device_id = Build.SERIAL;
	static  int region= ProductInfo.getInstance().region;
	static String title=null;
	static  int emoji=1;
//	static int bofang_time=0;

	private static final int MSG_PLAY_PROGRESS = 1;
	private static final int PLAY_MESSAGE=2;

	private int mContentCode = 0;
	private int mCateCode = 0;
	private String mCateName = "";
	private String mTitle = "";

	private boolean LEFT_ON=false;
	private boolean RIGHT_ON=false;

	private boolean IF_GONE=false;

	private KeyEvent mLastEvent = null;
	private KeyEvent mDownEvent = null;
	private int mStateFastSeek = STATE_FAST_SEEK_IDLE;

	private long KUAIJIN_TIME=0;
	private RelativeLayout login_daka_relayout;
	private ImageView fit_daka_gou1;
	private ImageView fit_daka_gou2;
	private ImageView fit_daka_gou3;

	private ImageView fit_daka_face1;
	private ImageView fit_daka_face2;
	private ImageView fit_daka_face3;

	private ImageView fit_daka_queding;
	int time=0;

	private TextView fit_daka_name;
	private TextView fit_daka_time;
	private TextView fit_daka_col;

	private CircleImageView fit_daka_touxiang;
	private int biaoqing_num=3;
	String content_code="";
	String cate_code="";
	String userid="";
	String username="";
	String userurl="";
	private int bofang_time=0;
	private String title_lanmu="";
	 public static Boolean IS_YULAN=false;
	int mTime=0;
	int endtime=0;
	private TextView time_tv1;
	private TextView time_tv2;

	Handler mHandler = new Handler(Looper.getMainLooper()) {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case MSG_PLAY_PROGRESS:
					//do something;
					if(pro_mid.getVisibility()==View.VISIBLE) {
						try {
							if (mediaPlayer.getCurrentPosition() > 0) {
								pro_mid.setVisibility(View.GONE);
							}
						}catch (IllegalStateException e){
							e.printStackTrace();
						}
					}
					try{
					if (mediaPlayer!=null&&mediaPlayer.isPlaying()) {
						playprogressbar.setProgress(mediaPlayer.getCurrentPosition());
						//Log.d("Simple==",mediaPlayer.getCurrentPosition()+"=="+mediaPlayer.isPlaying());
						//Toast.makeText(getApplicationContext(),mediaPlayer.getCurrentPosition()+"=="+mediaPlayer.isPlaying(),Toast.LENGTH_SHORT).show();
						kaluli+=0.1;
						duration+=1;
						bofang_time=mediaPlayer.getCurrentPosition();
						int b1=bofang_time/1000;
						int s=b1%60;
						int m=b1/60;
						String ss=null;
						if(s<10){
							ss="0"+s;
						}else{
							ss=s+"";
						}
						time_tv1.setText(m+":"+ss);
						SharedPreferences sp = SimplewudaoPlayerActivity.this.getSharedPreferences("wanba_config", Context.MODE_PRIVATE);
						SharedPreferences.Editor editor = sp.edit();
						editor.putInt("duration",duration);
						editor.apply();
//						UserCenterActivity.kaluli=kaluli;
						BigDecimal b  =   new BigDecimal(kaluli);
						float   f   =  b.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
						int time_num=bofang_time/1000;
						int min=time_num/60;
						int col=time_num*335/3600;
						kaluli_tv.setText(col+"");
					}else{

					}
				}catch (IllegalStateException e){
						e.printStackTrace();
				}

					mHandler.removeMessages(MSG_PLAY_PROGRESS);
					mHandler.sendEmptyMessageDelayed(MSG_PLAY_PROGRESS, 1000);
					break;

				case PLAY_MESSAGE:
					try{
//						Log.d("Simple##",mediaPlayer+"    ==   "+mediaPlayer.isPlaying());
						if(mediaPlayer != null && mediaPlayer.isPlaying()){
						if(!IF_GONE) {
							all_gone();
						}

					}else{

					}
					}catch (IllegalStateException e){
						e.printStackTrace();
					}catch (Exception e){
					//	Toast.makeText(getApplicationContext(),""+IF_GONE,Toast.LENGTH_LONG).show();
						e.printStackTrace();
					}
					mHandler.removeMessages(PLAY_MESSAGE);
					mHandler.sendEmptyMessageDelayed(PLAY_MESSAGE, 3500);
					IF_GONE=false;
					break;
			}
		}
	};


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_simple_player);
		Log.d("@@anr","simcreate");
		appName = getResources().getString(R.string.app_name);
		loading = getResources().getString(R.string.info_loading);

		exitInfo = getResources().getString(R.string.info_exit);

		kaluli_tv=(TextView)findViewById(R.id.kaluli_tv1);
		login_daka_relayout=(RelativeLayout)findViewById(R.id.login_daka_relayout);
		fit_daka_gou1=(ImageView)findViewById(R.id.login_daka_gou1);
		fit_daka_gou2=(ImageView)findViewById(R.id.login_daka_gou2);
		fit_daka_gou3=(ImageView)findViewById(R.id.login_daka_gou3);
		fit_daka_face1=(ImageView)findViewById(R.id.login_daka_face1);
		fit_daka_face2=(ImageView)findViewById(R.id.login_daka_face2);
		fit_daka_face3=(ImageView)findViewById(R.id.login_daka_face3);
		fit_daka_queding=(ImageView)findViewById(R.id.login_daka_queding);
		fit_daka_gou1.setVisibility(View.GONE);
		fit_daka_gou2.setVisibility(View.GONE);
		final Intent intent = getIntent();
		if (intent != null) {
			if(intent.getStringExtra("cate_code")!=null) {
				mCateCode = Integer.parseInt(intent.getStringExtra("cate_code"));
			}
			if(intent.getStringExtra("content_code")!=null) {
				mContentCode = Integer.parseInt(intent.getStringExtra("content_code"));
			}
				mTitle = intent.getStringExtra("title");
				mCateName = intent.getStringExtra("cate_name");

		}


		bofang_view=(View)findViewById(R.id.bofang_view);
		playstat=(ImageView)findViewById(R.id.play_stat);
		playstop=(ImageView)findViewById(R.id.play_stop);
		playback=(ImageView)findViewById(R.id.play_back);
		playgo=(ImageView)findViewById(R.id.play_go);

		surfaceView = (SurfaceView) findViewById(R.id.simple_video_view);


		final SurfaceHolder surfaceHolder = surfaceView.getHolder();
		surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		playprogressbar = (ProgressBar) findViewById(R.id.play_progressbar);
		time_tv1 = ((TextView) findViewById(R.id.time_tv1));
		time_tv2 = ((TextView) findViewById(R.id.time_tv2));
		pro_mid=(ProgressBar)findViewById(R.id.pro_mid);

		surfaceHolder.addCallback(new SurfaceHolder.Callback() {
			@Override
			public void surfaceCreated(SurfaceHolder holder) {
				Log.d("@@anr","simsurfaceCreated");
				try {
					mediaPlayer = new WanbaMediaPlayer();
					mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
					@Override
					public void onPrepared(MediaPlayer mp) {
						time=mediaPlayer.getDuration();
						if (mediaPlayer!=null){
							mediaPlayer.start();
						}

						DataReport.ContentInformation(SimplewudaoPlayerActivity.this,"1200",mCateCode+"",mContentCode+"",mTitle,"0");

						if(KUAIJIN_TIME>0){
							mediaPlayer.seekTo((int)KUAIJIN_TIME);
						}
						Behavior.onPlayContentStart(SimplewudaoPlayerActivity.this, mCateCode, mCateName, mContentCode, mTitle);
						playprogressbar.setMax(mediaPlayer.getDuration());
						mTime=mediaPlayer.getDuration();
						Log.d("Simple==",mTime+"");
						//		mThread.start();
						mHandler.sendEmptyMessage(MSG_PLAY_PROGRESS);
						mHandler.sendEmptyMessage(PLAY_MESSAGE);
						int b=time/1000;
						int s=b%60;
						int m=b/60;
						String ss=null;
						if(s<10){
							ss="0"+s;
						}else{
							ss=s+"";
						}
						time_tv2.setText(m+":"+ss);
						Log.d("Simple==","sendMessage");

					}
				});

				mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
					@Override
					public void onCompletion(MediaPlayer mp) {
						Log.d("Simple==","completion");
						isRunning = false;
						Behavior.onPlayContentStop(SimplewudaoPlayerActivity.this,mCateCode,mCateName,mContentCode,mTitle);
						DataReport.EventInformation(SimplewudaoPlayerActivity.this,"3300","000003","{\"contentcode\":"+mContentCode+",\"categorycode\":"+mCateCode+",\"duration\":"+mTime+"}");
						endtime=mTime;
						mediaPlayer.release();

						title = SimplewudaoPlayerActivity.this.getSharedPreferences("wanba_config", Context.MODE_PRIVATE).getString("title", null);

					}
				});

				mediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
					@Override
					public void onBufferingUpdate(MediaPlayer mp, int percent) {
						playprogressbar.setSecondaryProgress((int) (mediaPlayer.getDuration() * ((float) percent / 100)));
					}
				});

				mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
				mediaPlayer.setDisplay(surfaceHolder);
				Log.d("Simple==","display"+mediaPlayer);

				final String playUrl = SimplewudaoPlayerActivity.this.getIntent().getStringExtra("play_url");
				Log.d("Simple==","=="+playUrl);
				title_lanmu = SimplewudaoPlayerActivity.this.getIntent().getStringExtra("title_lanmu");
				content_code=SimplewudaoPlayerActivity.this.getIntent().getStringExtra("content_code");
				cate_code=SimplewudaoPlayerActivity.this.getIntent().getStringExtra("cate_code");
//					Toast.makeText(SimplewudaoPlayerActivity.this,title_lanmu,Toast.LENGTH_SHORT).show();
//			mediaPlayer.setDataSource(playUrl);

					mediaPlayer.setUrl(playUrl, new WanbaMediaPlayer.OnCheckFinishCallback() {
						@Override
						public void onCheckFinish(boolean success) {
							Log.d("Simple==", "success" + success + "==" + mediaPlayer);
							prepare();
						}
					});
				}catch (IOException e){
					e.printStackTrace();
				}
			}
			void  prepare(){
				mediaPlayer.prepareAsync();
				Log.d("Simple==","pre");
				mediaPlayer.setVolume(0.5f, 0.5f);
			}

			@Override
			public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

			}

			@Override
			public void surfaceDestroyed(SurfaceHolder holder) {
				Log.d("@@anr","simplesurdestroy");
				mHandler.removeMessages(MSG_PLAY_PROGRESS);
				if (mediaPlayer != null) {
					Behavior.onPlayContentStop(SimplewudaoPlayerActivity.this, mCateCode, mCateName, mContentCode, mTitle);
					mediaPlayer.release();
					mediaPlayer = null;
				}
			}
		});


		playstat.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Log.d("caozuo","stat");
				//if (mediaPlayer!=null) {
					//IF_GONE=true;
				if (!mediaPlayer.isPlaying()){
					IF_GONE=true;
					playstop.setVisibility(View.VISIBLE);
					playstat.setVisibility(View.GONE);
					playstop.requestFocus();
					mediaPlayer.start();
					Behavior.onPlayContentStart(SimplewudaoPlayerActivity.this, mCateCode, mCateName, mContentCode, mTitle);
				}

				//} else {

				//}

			}
		});

		playstop.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Log.d("caozuo","stop");
				IF_GONE=true;
				if(mediaPlayer.isPlaying()) {
					playstat.setVisibility(View.VISIBLE);
					playstop.setVisibility(View.GONE);
					playstat.requestFocus();
					mediaPlayer.pause();
					Behavior.onPlayContentStop(SimplewudaoPlayerActivity.this, mCateCode, mCateName, mContentCode, mTitle);
				}
			}
		});
		playback.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				IF_GONE=true;
				if(mediaPlayer.isPlaying()) {
					mediaPlayer.seekTo(mediaPlayer.getCurrentPosition() - 10000);
				}else{
					KUAIJIN_TIME-=10000;
					mediaPlayer.seekTo(mediaPlayer.getCurrentPosition() - 10000);
					playprogressbar.setProgress(mediaPlayer.getCurrentPosition());
				}
			}
		});
		playgo.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				IF_GONE=true;
				if(mediaPlayer.isPlaying()) {
					mediaPlayer.seekTo(mediaPlayer.getCurrentPosition() + 10000);
				}else{
					KUAIJIN_TIME+=10000;
					mediaPlayer.seekTo(mediaPlayer.getCurrentPosition() + 10000);
					playprogressbar.setProgress(mediaPlayer.getCurrentPosition());
				}
			}
		});
		if(LoginWudaoActivity.LANMU_NUM==5){
			login_daka_relayout.setBackgroundResource(R.drawable.login_daka_bengbengtiao_bg);
		}else if(LoginWudaoActivity.LANMU_NUM==6){
			login_daka_relayout.setBackgroundResource(R.drawable.login_daka_wangguangcheng_bg);
		}
		else if(LoginWudaoActivity.LANMU_NUM==7){
			login_daka_relayout.setBackgroundResource(R.drawable.login_daka_jiewu_bg);
		}else if(LoginWudaoActivity.LANMU_NUM==8){
			login_daka_relayout.setBackgroundResource(R.drawable.login_daka_dupiwu_bg);
		}
		fit_daka_face1.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				fit_daka_gou1.setVisibility(View.VISIBLE);
				fit_daka_gou2.setVisibility(View.GONE);
				fit_daka_gou3.setVisibility(View.GONE);
			}
		});
		fit_daka_face2.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				fit_daka_gou1.setVisibility(View.GONE);
				fit_daka_gou2.setVisibility(View.VISIBLE);
				fit_daka_gou3.setVisibility(View.GONE);
			}
		});
		fit_daka_face3.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				fit_daka_gou1.setVisibility(View.GONE);
				fit_daka_gou2.setVisibility(View.GONE);
				fit_daka_gou3.setVisibility(View.VISIBLE);
			}
		});

		fit_daka_queding.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (fit_daka_gou1.getVisibility() == View.VISIBLE) {
					biaoqing_num = 1;
				} else if (fit_daka_gou2.getVisibility() == View.VISIBLE) {
					biaoqing_num = 2;
				} else {
					biaoqing_num = 3;
				}
				post_shangchuan();
				Behavior.onEvent(SimplewudaoPlayerActivity.this, 3050005, "播放页面打卡");
				login_daka_relayout.setVisibility(View.GONE);
				DataReport.PageRetreat(SimplewudaoPlayerActivity.this, "2100", "300003");
				if(endtime!=0) {
					DataReport.ContentInformation(SimplewudaoPlayerActivity.this, "2200", mCateCode + "", mContentCode + "", mTitle, mTime+ "");
					int time_num=mTime/1000;
					int min=time_num/60;
					final int col=time_num*335 / 3600;
					DataReport.EventInformation(SimplewudaoPlayerActivity.this,"3300","000002","{\"emoji\":"+biaoqing_num+",\"duration\":"+mTime +",\"cal\":"+col+"}");

				}else {
					DataReport.ContentInformation(SimplewudaoPlayerActivity.this, "2200", mCateCode + "", mContentCode + "", mTitle, mediaPlayer.getCurrentPosition()+"");
					int time_num=mediaPlayer.getDuration()/1000;
					int min=time_num/60;
					final int col=time_num*335 / 3600;
					DataReport.EventInformation(SimplewudaoPlayerActivity.this,"3300","000002","{\"emoji\":"+biaoqing_num+",\"duration\":"+mediaPlayer.getCurrentPosition() +",\"cal\":"+col+"}");
				}
				if (mediaPlayer!=null){
					mediaPlayer.release();
					mediaPlayer=null;
				}
				Log.d("@@mean","queding");
				finish();
			}
		});

		fit_daka_name=(TextView)findViewById(R.id.login_daka_name);
		fit_daka_time=(TextView)findViewById(R.id.login_daka_time);
		fit_daka_col=(TextView)findViewById(R.id.login_daka_col);
		fit_daka_touxiang=(CircleImageView)findViewById(R.id.login_daka_touxiang);

		RequestQueue rq1 = Volley.newRequestQueue(this.getApplicationContext());
		JsonObjectRequest request1 = new JsonObjectRequest("http://121.201.7.173:8063/proxy/61.191.46.214/8087/wanba/photo_ajax.jsp?userId="+ Util.getDeviceId(this), null,
				new Response.Listener<JSONObject>() {

					@Override
					public void onResponse(JSONObject jsonObject) {
						try {
							JSONArray arr=jsonObject.getJSONArray("userList");
							if (arr != null && arr.length() <= 0) {
								return;
							}
							JSONObject obj=arr.getJSONObject(0);
							String iv_url=obj.getString("portraitUrl");
							userurl=obj.getString("portraitUrl");
							userid=obj.getString("userId");
							fit_daka_name.setText(obj.getString("userName"));
							username=obj.getString("userName");
							RequestQueue mQueue = Volley.newRequestQueue(SimplewudaoPlayerActivity.this);
							ImageRequest imageRequest = new ImageRequest(
									iv_url,
									new Response.Listener<Bitmap>() {
										@Override
										public void onResponse(Bitmap response) {
											fit_daka_touxiang.setImageBitmap(response);
										}
									}, 0, 0, Bitmap.Config.RGB_565, new Response.ErrorListener() {
								@Override
								public void onErrorResponse(VolleyError error) {
//                                    erweima_login.setImageResource(R.drawable.default_image);
								}
							});
							mQueue.add(imageRequest);
						} catch (JSONException e) {
							e.printStackTrace();
						}

					}
				}, new Response.ErrorListener() {
			@Override
			public void onErrorResponse(VolleyError volleyError) {
			}
		}

		);
		request1.setRetryPolicy(new DefaultRetryPolicy(30000,3,1.0f));
		rq1.add(request1);

	}

	/**
	 * 向指定的服务器报告视频播放信息
	 * 暂时没有真正发送请求
	 * 如果需要请将加入队列的代码注释去掉
	 */
	public void jsonReport(String url) {
		JSONObject jsonRequest = new JSONObject();
		try {
			jsonRequest.put("cate_code", getIntent()
					.getStringExtra("cate_code"));
			jsonRequest.put("media_code",
					getIntent().getStringExtra("media_code"));
			jsonRequest.put("play_url", getIntent().getStringExtra("play_url"));
			jsonRequest.put("title_lanmu", getIntent().getStringExtra("title_lanmu"));
		} catch (JSONException e) {
			e.printStackTrace();
		}
		JsonObjectRequest request = new JsonObjectRequest(url, jsonRequest,
				null, null);
		// AppUtil.getInstance(SimplewudaoPlayerActivity.this).getRequestQueue()
		// .add(request);

	}

	public void exitPlay() {
		if ((System.currentTimeMillis() - exitTime) > 2000) {
			Toast.makeText(this, exitInfo, Toast.LENGTH_SHORT).show();
			exitTime = System.currentTimeMillis();
		} else {
			mediaPlayer.release();
			kaluli=0;
			Log.d("@@mean","exit");
			this.finish();
		}
	}



	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK)) {

			if(IS_YULAN){
				DataReport.ContentInformation(SimplewudaoPlayerActivity.this, "2200", mCateCode + "", mContentCode + "", mTitle, mediaPlayer.getCurrentPosition()  + "");
				mediaPlayer.release();
				DataReport.PageRetreat(SimplewudaoPlayerActivity.this, "2100", "300004");
				Log.d("@@mean","keydown");
				finish();
				IS_YULAN=false;
			}else {
				if(login_daka_relayout.getVisibility()==View.GONE){
					login_daka_relayout.setVisibility(View.VISIBLE);
					fit_daka_face3.requestFocus();
					playstat.setFocusable(false);
					playstop.setFocusable(false);
					playback.setFocusable(false);
					playgo.setFocusable(false);
					int time_num=bofang_time/1000;
					int min=time_num/60;
					int col=time_num * 335 / 3600;
//        fit_daka_name.setText("张国钰木有小JJ");
					fit_daka_time.setText(min+" min");
					fit_daka_col.setText(col+" col");
				}else{
					login_daka_relayout.setVisibility(View.GONE);
					playstat.setFocusable(true);
					playstop.setFocusable(true);
					playback.setFocusable(true);
					playgo.setFocusable(true);
				}
			}
//			SharedPreferences sp1 = SimplewudaoPlayerActivity.this.getSharedPreferences("wanba_config", Context.MODE_PRIVATE);
//			SharedPreferences.Editor editor = sp1.edit();
//			bofang_time=duration;
//			editor.putInt("bofang_time",bofang_time);
//			editor.apply();
//			kaluli=0;
//				finish();
//			}
			return true;
		}
		else if((keyCode == KeyEvent.KEYCODE_DPAD_LEFT)){
			if((playback.getVisibility()==View.INVISIBLE)){
				all_visible();
				IF_GONE=true;
				return true;
			}else {
				if (mStateFastSeek == STATE_FAST_SEEK_IDLE) {
					IF_GONE = true;
					mStateFastSeek = STATE_FAST_SEEK_PREPARED;

					mDownEvent = event;
				} else if (mStateFastSeek == STATE_FAST_SEEK_PREPARED) {

					final long deltaEventTime = event.getEventTime() - mDownEvent.getDownTime();
					if (deltaEventTime > 300) {
						mStateFastSeek = STATE_FAST_SEEK_START;
						mLastEvent = event;
						Log.d("KeyEvent", "@@@ onKeyDown at " + event.getEventTime());
						if(mediaPlayer.isPlaying()) {
							mediaPlayer.seekTo(mediaPlayer.getCurrentPosition() - 2000);
						}else{
							KUAIJIN_TIME-=2000;
							mediaPlayer.seekTo(mediaPlayer.getCurrentPosition() - 2000);
							playprogressbar.setProgress(mediaPlayer.getCurrentPosition());
						}
						IF_GONE = true;
					}
				} else if (mStateFastSeek == STATE_FAST_SEEK_START) {
					final long deltaEventTime = event.getEventTime() - mLastEvent.getEventTime();
					if (deltaEventTime > 100) {
						mLastEvent = event;
						Log.d("KeyEvent", "@@@ onKeyDown at " + event.getEventTime());
						if(mediaPlayer.isPlaying()) {
							mediaPlayer.seekTo(mediaPlayer.getCurrentPosition() - 2000);
						}else{
							KUAIJIN_TIME-=2000;
							mediaPlayer.seekTo(mediaPlayer.getCurrentPosition() - 2000);
							playprogressbar.setProgress(mediaPlayer.getCurrentPosition());
						}
						IF_GONE = true;
					}
				}

				return super.onKeyDown(keyCode, event);
			}
		}
		else if((keyCode == KeyEvent.KEYCODE_DPAD_RIGHT)){
			if((playback.getVisibility()==View.INVISIBLE)){
				all_visible();
				IF_GONE=true;
				return true;
			}else {
				if (mStateFastSeek == STATE_FAST_SEEK_IDLE) {
					IF_GONE = true;
					mStateFastSeek = STATE_FAST_SEEK_PREPARED;
					mDownEvent=event;
				} else if (mStateFastSeek == STATE_FAST_SEEK_PREPARED) {

					final long deltaEventTime = event.getEventTime() - mDownEvent.getDownTime();
					if (deltaEventTime > 300) {
						mStateFastSeek = STATE_FAST_SEEK_START;
						mLastEvent = event;
						Log.d("KeyEvent", "@@@ onKeyDown at " + event.getEventTime());
						if(mediaPlayer.isPlaying()) {
							mediaPlayer.seekTo(mediaPlayer.getCurrentPosition() + 2000);
						}else{
							KUAIJIN_TIME+=2000;
							mediaPlayer.seekTo(mediaPlayer.getCurrentPosition() + 2000);
							playprogressbar.setProgress(mediaPlayer.getCurrentPosition());
						}
						IF_GONE = true;
					}
				} else if (mStateFastSeek == STATE_FAST_SEEK_START) {
					final long deltaEventTime = event.getEventTime() - mLastEvent.getEventTime();
					if (deltaEventTime > 100) {
						mLastEvent = event;
						Log.d("KeyEvent", "@@@ onKeyDown at " + event.getEventTime());
						if(mediaPlayer.isPlaying()) {
							mediaPlayer.seekTo(mediaPlayer.getCurrentPosition() + 2000);
						}else{
							KUAIJIN_TIME+=2000;
							mediaPlayer.seekTo(mediaPlayer.getCurrentPosition() + 2000);
							playprogressbar.setProgress(mediaPlayer.getCurrentPosition());
						}
						IF_GONE = true;
					}
				}
				return super.onKeyDown(keyCode, event);
			}
		}
		else {
			if((playback.getVisibility()==View.INVISIBLE)){
				all_visible();
				IF_GONE=true;
				return true;
			}else {
				IF_GONE=true;
				return super.onKeyDown(keyCode, event);
			}
		}
	}

	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		if((keyCode == KeyEvent.KEYCODE_DPAD_LEFT)) {
			if (mStateFastSeek == STATE_FAST_SEEK_START) {
				mStateFastSeek = STATE_FAST_SEEK_IDLE;
				mLastEvent = null;
				mDownEvent = null;
			}
		}
		return super.onKeyUp(keyCode, event);
	}





	public boolean onError(MediaPlayer mp, int what, int extra) {
//		mp.release();
		kaluli=0;
		Log.d("@@mean","error");
		finish();
		return false;
	}
	public void all_gone(){

		bofang_view.setVisibility(View.INVISIBLE);
		playstat.setVisibility(View.INVISIBLE);
		playstop.setVisibility(View.INVISIBLE);
		playback.setVisibility(View.INVISIBLE);
		playgo.setVisibility(View.INVISIBLE);
		time_tv1.setVisibility(View.INVISIBLE);
		time_tv2.setVisibility(View.INVISIBLE);
		playprogressbar.setVisibility(View.INVISIBLE);
	}
	public void all_visible(){
		bofang_view.setVisibility(View.VISIBLE);
		playstop.setVisibility(View.VISIBLE);
		playback.setVisibility(View.VISIBLE);
		playgo.setVisibility(View.VISIBLE);
		time_tv1.setVisibility(View.VISIBLE);
		time_tv2.setVisibility(View.VISIBLE);
		playprogressbar.setVisibility(View.VISIBLE);
	}
	private AlertDialog myDialog = null;
//	private void creatAlertDialog() {
//
//		myDialog = new AlertDialog.Builder(this).create();
//
//		myDialog.show();
//
//		myDialog.getWindow().setContentView(R.layout.diolag_daka);
//
//		myDialog.getWindow()
//				.findViewById(R.id.daka_button1)
//				.setOnClickListener(new View.OnClickListener() {
//
//					@Override
//					public void onClick(View v) {
//						Behavior.onEvent(SimplewudaoPlayerActivity.this,3050005,"播放页面打卡");
////						if (daka_gou1.getVisibility() == View.VISIBLE) {
////							emoji = 1;
////						} else if (daka_gou2.getVisibility() == View.VISIBLE) {
////							emoji = 2;
////						} else if (daka_gou3.getVisibility() == View.VISIBLE) {
////							emoji = 3;
////						} else if (daka_gou4.getVisibility() == View.VISIBLE) {
////							emoji = 4;
////						} else {
////							emoji = 5;
////						}
////						title = SimplewudaoPlayerActivity.this.getSharedPreferences("wanba_config", Context.MODE_PRIVATE).getString("title", null);
////						duration = SimplewudaoPlayerActivity.this.getSharedPreferences("wanba_config", Context.MODE_PRIVATE).getInt("duration", 0);
////
////						emoji = SimplewudaoPlayerActivity.this.getSharedPreferences("wanba_config", Context.MODE_PRIVATE).getInt("emoji", 0);
////						RequestQueue rq = Volley.newRequestQueue(SimplewudaoPlayerActivity.this.getApplicationContext());
////						try {
////							String urlEncoded = "http://61.191.46.214:8088/checkin/add?deviceid=" + device_id + "&emoji=" + emoji + "&duration=" + duration + "&region=" + region + "&title=" + URLEncoder.encode(title, "utf-8");
////							JsonObjectRequest request = new JsonObjectRequest(urlEncoded, null,
////									new Response.Listener<JSONObject>() {
////
////										@Override
////										public void onResponse(JSONObject jsonObject) {
////
////										}
////									}, new Response.ErrorListener() {
////								@Override
////								public void onErrorResponse(VolleyError volleyError) {
////								}
////							}
////
////							);
////
////							rq.add(request);
////						} catch (UnsupportedEncodingException e) {
////							e.printStackTrace();
////						}
//
//						SharedPreferences sp = SimplewudaoPlayerActivity.this.getSharedPreferences("wanba_config", Context.MODE_PRIVATE);
//						SharedPreferences.Editor editor = sp.edit();
//						SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
//						Date curDate = new Date(System.currentTimeMillis());//获取当前时间
//						String str = formatter.format(curDate);
//						editor.putString("time", str);
//						editor.apply();
//						myDialog.dismiss();
//						kaluli = 0;
//						finish();
//
//					}
//
//				});
//		myDialog.getWindow()
//				.findViewById(R.id.daka_button2)
//				.setOnClickListener(new View.OnClickListener() {
//
//					@Override
//					public void onClick(View v) {
//
//						myDialog.dismiss();
//						kaluli = 0;
//						finish();
//
//					}
//
//				});
//
//	}
	@Override
	protected void onResume() {
		super.onResume();
		Behavior.onPageResume(this, 300001, "播放页面");
	}

	@Override
	protected void onPause() {
		super.onPause();
		Behavior.onPagePause(this, 300001, "播放页面");
	}

	@Override
	protected void onStop() {
		super.onStop();
		try {
			mediaPlayer.release();
		}catch (Exception e){
			e.printStackTrace();
		}
	}

	@Override
	protected void onStart() {
		super.onStart();
		if(IS_YULAN){
			DataReport.PageRetreat(SimplewudaoPlayerActivity.this, "1100", "300004");
		}else{
			DataReport.PageRetreat(SimplewudaoPlayerActivity.this, "1100", "300003");
		}
	}

	private void post_shangchuan(){

		RequestQueue requestQueue = Volley.newRequestQueue(SimplewudaoPlayerActivity.this);
		String url="http://121.201.7.173:8063/proxy/61.191.46.214/8087/checkin/add";
		StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.POST,url,
				new Response.Listener<String>() {
					@Override
					public void onResponse(String response) {
						Log.e("zzzzz",response);
					}
				}, new Response.ErrorListener() {
			@Override
			public void onErrorResponse(VolleyError error) {
				error.printStackTrace();
			}
		}) {
			@Override
			protected Map<String, String> getParams() {
				//在这里设置需要post的参数
				Map<String, String> map = new HashMap<String, String>();
				map.put("deviceid",Util.getDeviceId(SimplewudaoPlayerActivity.this));
				map.put("emoji",biaoqing_num+"");
				map.put("duration",bofang_time/1000+"");
				map.put("region","23");
				map.put("title",title_lanmu);
				map.put("contentcode", content_code);
				map.put("category", cate_code);
				map.put("wxnickname",username);
				map.put("wxuserid",userid);
				map.put("wxportrait",userurl);
				return map;
			}
		};
		stringRequest.setRetryPolicy(new DefaultRetryPolicy(30000,3,1.0f));
		requestQueue.add(stringRequest);
	}
}
